import matplotlib.pyplot as plt
#创建数据
#make_blobs 聚类生成器
from sklearn.datasets.samples_generator import make_blobs
x, y_true = make_blobs(n_samples = 300, #生成300条数据
                       centers = 4, #4类数据
                       cluster_std = 0.5, #方差一致
                       random_state = 0) #随机数种子
x.shape #(300, 2)

#cluster_std 每个类别的方差，如多累数据不同方差，可设置为【1.0,3.0】(这里针对两类数据)
#x 生成数据值
#y 生成数据对应的类别标签

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters = 4)
kmeans.fit(x)
y_kmeans = kmeans.predict(x)

plt.scatter(x[:,0], x[:,1], c = y_kmeans, cmap='Dark2', s=50, alpha=0.5, marker='x')

centroids = kmeans.cluster_centers_
print(kmeans.labels_)
'''
plt.scatter(centroids[:,0], centroids[:,1],c=[0,1,2,3],cmap='Dark2',s=70, marker='o')
plt.title('K-means 300 points')
plt.xlabel('Value1')
plt.ylabel('Value2')
plt.grid()
plt.show()
'''